package com.block.datapush.form.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.model.dto.CountInfoDTO;
import com.block.common.service.ICountCommonService;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.datapush.form.enums.PushResultEnum;
import com.block.datapush.form.factory.FormPushFactory;
import com.block.datapush.form.service.IDataPushFormService;
import com.block.datapush.form.service.IFormInfoHisService;
import com.block.datapush.form.service.IFormInfoItemService;
import com.block.datapush.model.dto.FormItemDTO;
import com.block.datapush.model.dto.FormPushResultDTO;
import com.block.db.entity.FormInfo;
import com.block.db.entity.FormInfoHis;
import com.block.db.entity.MemberExtInfo;
import com.block.db.mapper.FormInfoHisMapper;
import com.block.db.mapper.FormInfoMapper;
import com.block.risk.enums.RiskDataTypeEnum;
import com.block.risk.service.IRiskHandlerService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

@Service
public class DataPushFormService implements IDataPushFormService {

    private static final Logger log = LogFactory.getPushLog();

    @Resource
    FormInfoMapper formInfoMapper;
    @Resource
    FormInfoHisMapper formInfoHisMapper;
    @Autowired
    IFormInfoItemService formInfoItemService;
    @Autowired
    NotifyExceptionService notifyExceptionService;
    @Autowired
    IFormInfoHisService formInfoHisService;
    @Autowired
    IRiskHandlerService riskHandlerService;
    @Autowired
    ICountCommonService countCommonService;

    /**
     * 进行订单推送
     */
    @Async
    @Override
    public void dataPushHandle(MemberExtInfo memberExtInfo) {

        // 查询可用的表单推送信息
        String nowTime = LocalDateUtil.getNowDateStr(LocalDateUtil.SIMPLE_TIME);
        String nowDate = LocalDate.now().toString();
        List<FormInfo> fromInfoList =  this.formInfoMapper.findEnableChannelInfo(nowTime, nowDate);

        for (FormInfo formInfo: fromInfoList){
            try {
                boolean pushData = this.toPushData(formInfo, memberExtInfo, "SYS");
            }catch (Exception exception){
                exception.printStackTrace();
                log.error("【表单推送】推送异常", exception);
                notifyExceptionService.notifyNoticeInfo("pushFormExc","api推送异常", memberExtInfo.getUid() + "======"+formInfo.getChannelName(),exception);
            }
        }
    }

    /**
     * 表单推送数据
     * @param formInfo
     * @param memberExtInfo
     */
    @Override
    public boolean toPushData(FormInfo formInfo, MemberExtInfo memberExtInfo, String pushType) throws Exception {

        // 判断是否已经存在没推送过的历史
        FormInfoHis existHisInfo = formInfoHisMapper.getEntityByFormIdAndUid(memberExtInfo.getUid(), formInfo.getId());
        if (ObjectUtil.isNotEmpty(existHisInfo)){
            log.info("【表单推送】该表单已经推送过该用户【formName】{}【uid】{}", formInfo.getChannelName(), memberExtInfo.getUid());
            return false;
        }else {
            // 初始化 推送历史信息
            existHisInfo = formInfoHisService.initFormInfoHis(formInfo, memberExtInfo, pushType);
        }

        // 判断是否可以推送数据
        FormItemDTO formItemDTO = formInfoItemService.canPushMemberInfo(formInfo, memberExtInfo);
        if (!formItemDTO.isCanPush()){
            formInfoHisService.updateFormInfoHis(existHisInfo, PushResultEnum.FILTER_ERROR, null, null);
            log.info("【表单推送】没有可用的推送item信息【formName】{}【uid】{}", formInfo.getChannelName(), memberExtInfo.getUid());
            return false;
        }

        // 查询撞库结果
        boolean matchResult = FormPushFactory.getService(formInfo.getType()).queryMatchResult(formInfo, memberExtInfo);
        log.info("【表单推送】【撞库完成】【result】{}【formType】{}【uid】{}", matchResult, formInfo.getType(), memberExtInfo.getUid());
        //  记录撞库数量
        if (!matchResult){
            formInfoHisService.updateFormInfoHis(existHisInfo, PushResultEnum.MATCH_ERROR, null, null);
            return false;
        }

//        if (ObjectUtil.equals(formInfo.getRiskFlag(), Integer.valueOf(1))){
//            boolean riskResult = riskHandlerService.dataRiskControlHandle(memberExtInfo, String.valueOf(formInfo.getId()), RiskDataTypeEnum.FORM.getValue());
//            if (!riskResult){
//                // 更新推送记录
//                formInfoHisService.updateFormInfoHis(existHisInfo, PushResultEnum.RISK_ERROR, null, null);
//                log.info("【表单推送】风控没有通过【formName】{}【uid】{}", formInfo.getChannelName(), memberExtInfo.getUid());
//                return false;
//            }
//        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("itemId", formItemDTO.getItemId());

        // 撞库成功，创建推送记录
        // 进行表单推送操作
        FormPushResultDTO pushResultDTO  = FormPushFactory.getService(formInfo.getType()).pushMemberInfo(formInfo, memberExtInfo, String.valueOf(existHisInfo.getId()), jsonObject);
        log.info("【表单推送】推送结束【pushResultDTO】{}", JSON.toJSONString(pushResultDTO));

        PushResultEnum entityByType = PushResultEnum.getEntityByType(pushResultDTO.getPushResult());

        formInfoHisService.updateFormInfoHis(existHisInfo, entityByType, pushResultDTO, formItemDTO);

        if (StrUtil.equals(pushResultDTO.getPushResult(), PushResultEnum.SUCCESS.getType())){
            CountInfoDTO countInfoDTO = new CountInfoDTO(memberExtInfo.getChannelCode());
            countInfoDTO.setFormPushCount(1);
            countInfoDTO.setFormPushAmount(formItemDTO.getPriceAmount());
            countCommonService.calculateDataInfo2(countInfoDTO);
        }
        return true;
    }

}
